package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.zline.foodraise.R;
import com.zline.foodraise.alipay.AlipayUtil;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.JsOrderCommentBean;
import com.zline.foodraise.js.HostJSScope;
import com.zline.foodraise.js.MyWebViewSetting;
import com.zline.foodraise.listener.CanChildScrollUpCallback;
import com.zline.foodraise.listener.JsInvokeListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.URLUtils;
import com.zline.foodraise.view.ScrollSwipeRefreshLayout;
import com.zline.foodraise.wx.WxPayUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/8/10.
 * 商品订单列表
 */
@EActivity(R.layout.activity_web)
public class ProductOrderActivity extends ZlineActivity implements JsInvokeListener,CanChildScrollUpCallback{
    private static final String LOG_TAG = ProductOrderActivity.class.getSimpleName();
    @ViewById(R.id.activity_web_wv)
    WebView wv;
    @ViewById(R.id.activity_web_srl)
    ScrollSwipeRefreshLayout swipeRefreshLayout;
    MyWebViewSetting mSetting;
    @StringRes(R.string.product_orders)
    String title;
    @ViewById(R.id.app_common_header_left_icon_iv)
    ImageView back_iv;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_iv;
    @Pref
    AppPref_ appPref;
    @Bean
    HostJSScope hostJSScope;
    @Bean
    WxPayUtil wxPayUtil;
    @Bean
    AlipayUtil alipayUtil;
    @Bean
    URLUtils urlUtils;
    @Extra
    int orderStatus;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    //点击重试
    boolean isReLoad = false;
    //加载出错
    boolean isErro = false;

    @AfterViews
    void doSomeAfterViews() {
        initHeader();
        initWebView();
        initSwipRefreshLayout();
    }

    void initHeader() {
        title_iv.setText(title);
    }

    void initWebView() {
        mSetting = new MyWebViewSetting(wv, this);
        mSetting.setWebView();
        String url = appPref.rootUrl().get() + Constant.PRODUCT_ORDER_URL+orderStatus;
        hostJSScope.setJsInvokeListener(this);
        wv.loadUrl(url);
        wv.setWebViewClient(new WebViewClient() {
            //出错界面
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                showErroView();
                LUtil.i(LOG_TAG, "______________erroCode________" + description);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LUtil.i(LOG_TAG, "_________shouldOverrideUrlLoading________" + url);
                doLinkUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                LUtil.i(LOG_TAG, "_________onPageStarted________" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LUtil.i(LOG_TAG, "____Host_____onPageFinished________" + url);
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }

                if (isReLoad && !isErro) {
                    exception_fl.setVisibility(View.GONE);
                    exception_rl.setVisibility(View.GONE);
                    wv.setVisibility(View.VISIBLE);
                }
                isErro = false;
                isReLoad = false;
                stopRefresh();
            }
        });

    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setCanChildScrollUpCallback(this);
        swipeRefreshLayout.setEnabled(false);//暂时停用刷新功能
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                wv.reload();
            }
        });
    }

    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }




    //显示网页加载出错情况
    void showErroView() {
        isErro = true;
        exception_fl.setVisibility(View.VISIBLE);
        exception_rl.setVisibility(View.VISIBLE);
        wv.setVisibility(View.GONE);
    }



    @Override
    public void jsInvoke(int flag) {
        switch (flag) {
            case Constant.WEB_JUMP_EAT_PAGE:
                MainActivity_.intent(this).fragmentIndex(1).start();
                break;
            default:
                break;
        }
    }

    @Override
    public void jsInvoke(int flag, JSONObject jsonObject) {
        switch (flag) {
            case Constant.WEB_ADD_COMMENT_FLAG:
                gotoAddComment(jsonObject);
                break;
            case Constant.WEB_PAY_FLAG:
                pay(jsonObject);
                break;
            default:
                break;
        }

    }

    @Override
    public void jsInvoke(double marginTop) {

    }


    //支付
    void pay(JSONObject jsonObject){
        try {
            if (jsonObject.opt(Constant.ONLINE_PAY_METHOD) != null &&
                    !jsonObject.isNull(Constant.ONLINE_PAY_METHOD) &&
                    jsonObject.get(Constant.ONLINE_PAY_METHOD) != JSONObject.NULL) {
                int payMethod = jsonObject.getInt(Constant.ONLINE_PAY_METHOD);
                if (payMethod == 4) {
                    //微信支付
                    wxPayUtil.pay(jsonObject);
                } else if (payMethod == 5) {
                    //支付宝支付
                    alipayUtil.pay(jsonObject,ProductOrderActivity.this);
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //给商品添加评论
    void gotoAddComment(JSONObject jsonObject) {
        String info=jsonObject.toString();
        Gson gson=new Gson();
        JsOrderCommentBean jsOrderCommentBean=gson.fromJson(info,JsOrderCommentBean.class);
        ReleaseProductCommentActivity_.intent(this)
                .jsOrderCommentBean(jsOrderCommentBean)
                .startForResult(Constant.PRODUCT_ORDER_REQUEST_CODE);
    }


    //处理带跳转链接的url
    void doLinkUrl(String url) {
        String goal = urlUtils.getUrlJumpTo(url);
        if (goal.equals("ccOrder-detail")) {//商品订单详情界面
            ProductOrderDetailActivity_.intent(ProductOrderActivity.this).url(url).start();
        } else if (goal.equals("ccOrder-list")) {//重新加载商品订单列表页
            wv.loadUrl(url);
        }

    }


    @OnActivityResult(Constant.PRODUCT_ORDER_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data) {
        switch (resultCode) {
            case Constant.ORDER_COMMENT_RESULT_CODE:
                LUtil.i(LOG_TAG,"________111111_________");
                //刷新页面
                wv.reload();
                break;
            default:
                break;
        }
    }



    @Click({R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void OnClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                isReLoad = true;
                wv.reload();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        hostJSScope.setJsInvokeListener(this);
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.PRODUCT_ORDER_LIST);
    }

    @Override
    protected void onPause() {
        super.onPause();
        hostJSScope.setJsInvokeListener(null);
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.PRODUCT_ORDER_LIST);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        return wv.getScrollY()> Constant.WEBVIEW_SCROLL_Y;
    }
}
